<template>
	<gracePage :customHeader="false">
		<!-- 页面主体 -->
		<view slot="gBody">
			<view style="background-color:#36395A;">
				<!-- 音乐播放器 -->
				<view class="grace-player">
					<view class="grace-player-title" :style="{color:color}">{{lists[index].title}}</view>
					<view class="grace-player-poster">
						<image class="grace-player-poster-img" :class="[playStatus == 1 ? 'grace-playing' : '']" 
						:src="lists[index].coverImgUrl" mode="aspectFill"></image>
					</view>
					<!-- 播放进度 -->
					<view style="padding:25rpx;">
						<view class="progress-bar" :style="{height: height,backgroundColor:dsColor}">
							<view class="progress" :style="{width: processTemp+'%', backgroundColor: bgColor,borderRadius: borderRadius}">
							</view>
							<text class="grace-sg-slider-bar"
							:style="{
								width:'170rpx', height:'44rpx', 'line-height':'30rpx', 
								backgroundImage:bgColor, color:'#5cb85c', left:'75%', 
								borderRadius:borderRadius
							}">{{playTime}}/{{totalTime}}</text>
						</view>
					</view>
					<!-- 播放控制 -->
					<view class="grace-player-console">
						<!-- 循环模式 -->
						<view class="grace-player-tool" @tap="changeType">
							<text class="grace-player-tool graceplayer-icons" v-if="dotype == 1">&#xe677;</text>
							<text class="grace-player-tool graceplayer-icons" v-if="dotype == 2" style="font-size:40rpx;">&#xe636;</text>
						</view>
						
						<view class="grace-player-console-c">
							<!-- 前一曲 -->
							<text class="grace-player-tool graceplayer-icons" @tap="prev">&#xe659;</text>
							<!-- 播放/暂停 -->
							<text class="grace-player-tool graceplayer-icons" style="font-size:66rpx;" @tap="pause" v-if="playStatus == 1">&#xe62a;</text>
							<text class="grace-player-tool graceplayer-icons" style="font-size:66rpx;" @tap="playi" v-if="playStatus == 2">&#xe618;</text>
							<!-- 后一曲 -->
							<text class="grace-player-tool graceplayer-icons" @tap="next">&#xe65a;</text>
						</view>
						<!-- 播放列表按钮 -->
						<text class="grace-player-tool graceplayer-icons" @tap="openList">&#xe60f;</text>
					</view>
					<!-- 歌曲列表 -->
					<view class="grace-shade" :style="{left:listShow?'0':'-2000px'}" 
					@tap.stop.parent="hideList" @touchmove.stop.parent="">
						<scroll-view scroll-y="true" class="graceplayer-list" 
						:style="{background:listBg, height:listHeight}">
							<view class="graceplayer-list-item">题目列表</view>
							<view class="graceplayer-list-item" 
							:class="[index == idx ? 'graceplayer-list-item-this' : '']" 
							v-for="(item, idx) in lists" :key="idx" 
							@tap="playList" :data-index="idx">{{item.title}}</view>
						</scroll-view>
					</view>
					
					<view class="grace-body" style="background-color: #ffffff">
						<view class="demo">
							<view>
								<button type="primary" class="grace-button" size="mini" @tap="yuanWen">原文</button>
							</view>
							<view>
								<button type="primary" class="grace-button" size="mini" @tap="fanYi">翻译</button>
							</view>
							<!-- <view>
								<button type="primary" class="grace-button" size="mini">录音</button>
							</view>
							<view>
								<button type="primary" class="grace-button" size="mini">录播</button>
							</view> -->
						</view>
						
						<view v-if="yuanWenDisplay">
							<view class="grace-margin-top">
								<text class="grace-title">原文</text>
							</view>
							<view style="background-color: #dadada;">
								<text  class="grace-h4">{{lists[index].field11.replace(/\\n/g,'\n')}}</text>

							</view>
						</view>
						<view v-if="fanYiDisplay">
							<view class="grace-margin-top">
								<text class="grace-title">翻译</text>
							</view>
							<view style="background-color: #dadada;">
								<text  class="grace-h4">{{lists[index].field14.replace(/\\n/g,'\n')}}</text>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		
		

	</gracePage>
</template>
<script>
var _self; 
import gracePage from "../../graceUI/components/gracePage.vue";

export default {
	data() {
		return {
			color      :'#FFFFFF',
			listBg     : '#292E35',
			listHeight : '880rpx',
			
			playStatus  : 1,//1播放 、2暂停
			player      : null,
			playTime    : '00:00',
			timer       : null,
			dotype      : 1,//1列表播放、2单曲循环
			index       : 0,
			listShow    : false,
			audioLength : 1,
			demo2:[
				{ name: '原文', value: '0', checked: true },
				{ name: '翻译', value: '1', checked: false }
			],
			yuanWenDisplay:false,
			fanYiDisplay:false,
			totalTime:'00:00',
			
			objects:[],//缓存题目作为用户试题的基础
			loadMoreText : "加载更多",
			showLoadMore : false,
			pageNum : 1,
			//每次加载的记录数
			pageSize : 10,
			//解决列表触底加载过程中服务器新增数据问题
			createTimeTo : "",
			token:"",
			swiperIndex:1,//swiper 当前下标
			show_hide:false,//题标是否隐藏 默认false 为隐藏
			istest:1,//1为练习 2为模拟 3为考试
			choice:[0,0,0],//[选择正确，选择错误，未答]
			lists : [ 
				{
				title: null,
				singer: null,
				epname: null,
				coverImgUrl: null,
				src: null,//文件
				field11:null,//原文
				field14:null,//翻译
				}
			],
			userInfoData : "",
			productionID:"",//课程ID
			production:"",
			topicImageSrc:"",//题目图片地址前缀
			changeTopicTipsState:true,//左右滑动切换题目提示
			studyCode:'',
			// 进度条
			//进度条颜色
			bgColor: '#2763b8',
			//进度条底色颜色
			dsColor: '#ffffff',
			//进度条高度
			height: '28rpx',
			//进度条圆角弧度
			borderRadius: '28rpx',
			//进度
			processTemp:0,
		}
	},

	onLoad: async function(e){
		uni.setNavigationBarColor({  
			frontColor: '#ffffff',  
			backgroundColor: '#36395A'
		});
		_self = this;
		_self.player = uni.getBackgroundAudioManager();
		
		//页面加载时读取一次缓存
		_self.userInfoData = _self.$myFunction.appStorage('wuLuUserInfo');
		//获取主题颜色
		_self.mainColor = _self.$myFunction.appConfig().mainColor;
		//获取应用名称
		_self.appName = _self.$myFunction.appConfig().appName;
		//记录时间，用于列表查询，必须在查询列表请求前获取时间
		_self.createTimeTo = _self.$myFunction.nowTime('Y-m-d H:i:s');
		
		//获取token，同步方法
		_self.token =  await _self.$myFunction.getToken();
		_self.token = _self.token.token;
		
		//生成成绩编码_打开试题即生成编码
		_self.studyCode = 'YSTK'+( _self.$myFunction.nowTime("Y-m-d H:i:s")).replace(/\s*/g,"").replace(/[:]/g, "").replace(/[-]/g, "");
		
		_self.topicImageSrc = _self.$myFunction.appConfig().serverIp+"resource/yunShangTianKong/topic/";
		
		//读取课程信息
		_self.productionID = e.id;
		// _self.productionID = 9;
		_self.getProductionList(_self.productionID);
	},
	onUnload(){
		clearInterval(_self.timer); //停止调用
		_self.player.stop()
		_self.playTime = '00:00';
		_self.totalTime = '00:00';
		_self.player.src ='';//当设置了新的 src 时，会自动开始播放
	},
	
	methods:{
		//播放进度
		progressChange : function(e){
			if(_self.timer != null){
				clearTimeout(_self.timer);
			}
			_self.player.pause();
			var needTime = _self.audioLength * e / 100;
			needTime = Math.round(needTime);
			_self.playTime = _self.timeFormat(needTime);
			_self.timer = setTimeout(()=>{
				_self.player.seek(needTime);
				_self.player.play();
			}, 800);
		},
		
		//时间显示
		timeFormat : function (s){
			s = Math.round(s);
			if(s < 60){
				if(s < 10){return '00:0'+s;}
				return '00:'+s;
			}else{
				var second = s % 60;
				s = s - second;
				var minute = s / 60;
				if(minute < 10){minute = '0'+minute;}
				if(second < 10){second = '0'+second;}
				return minute+':'+second;
			}
			
		},
		
		// 循环模式
		changeType : function () {
			switch(_self.dotype){
				case 1 :
				_self.dotype = 2;
				break;
				case 2 :
				_self.dotype = 1;
				break;
			}
		},
		// 暂停
		pause :function () {_self.player.pause();},
		// 播放
		playi :function () {_self.player.play();},
		
		//后一曲
		next : function () {
			if(_self.index + 1 >= _self.lists.length){uni.showToast({title:"已经到底了", icon:"none"}); return ;}
			_self.index++;
			_self.play();
		},
		// 前一曲
		prev : function () {
			if(_self.index -1 < 0){uni.showToast({title:"已经到头了", icon:"none"}); return ;}
			_self.index--;
			_self.play();
		},
		
		// 播放列表展示
		openList : function () { _self.listShow = true; },
		hideList : function () { _self.listShow = false; },
		// 点击列表曲目播放
		playList : function (e) {
			var idx = e.currentTarget.dataset.index;
			_self.index = idx;
			_self.play();
		},
		// 原文
		yuanWen:function(){
			_self.yuanWenDisplay = !_self.yuanWenDisplay;
		},
		// 翻译
		fanYi:function(){
			_self.fanYiDisplay = !_self.fanYiDisplay;
		},
		//播放
		play:function () {
			
			var audio                = _self.lists[_self.index];
			_self.player.title       = audio.title;
			_self.player.singer      = audio.singer;
			_self.player.coverImgUrl = audio.coverImgUrl;
			_self.player.src         = audio.src;
			_self.player.play();
		},

		playerInit:function(){
			
			// 注意 因为背景音频播放耗费手机电量，所以平台都有管控，需在manifest中填写申请。
			
			// ios App平台，背景播放需在manifest.json -> app-plus -> distribute -> ios 节点添加 "UIBackgroundModes":["audio"] 才能保证音乐可以后台播放（打包成ipa生效）
			// 小程序平台，需在manifest.json 对应的小程序节点下，填写"requiredBackgroundModes": ["audio"]。发布小程序时平台会审核
			// Android App端默认不会在通知栏出现音量控制，如需此功能，需要在插件市场单独下载原生插件
			// _self.player = uni.getBackgroundAudioManager();
			
			// 播放进度更新
			_self.player.onTimeUpdate(()=>{
				if(_self.playStatus != 1){return ;}
				// 调整进度
				var progress = _self.player.currentTime / _self.audioLength;
				progress = Math.round(progress * 100);
				_self.playTime = _self.timeFormat(_self.player.currentTime);
				_self.processTemp = progress;
				// console.log(_self.playTime);
			});
			
			//播放
			_self.player.onPlay(()=>{
				// console.log('play');
				_self.playStatus  = 1;
				// 当前音频的长度（单位：s），只有在当前有合法的 src 时返回
				_self.audioLength = _self.player.duration;
				_self.totalTime = _self.timeFormat(_self.audioLength);
			});
			
			// 暂停
			_self.player.onPause(()=>{
				// console.log('pause');
				_self.playStatus = 2;
			});
			
			//播放结束后循环播放
			_self.player.onEnded(()=>{
				// console.log('ended');
				switch(_self.dotype){
					case 1 :
						_self.index++;
						if(_self.index + 1 > _self.lists.length){_self.index = 0;}
						_self.play();
						break;
					case 2 :
						_self.player.seek(0);
						_self.play();
					break;
				}
			});
			
			//播放
			_self.play();
		},
	
		getProductionList: function(){
			uni.showToast({
				title: '请稍后...',
				duration:_self.$myFunction.appConfig().requestWaitTime,
				icon: 'none',
			});
			var params = {
				'id': _self.productionID
			};	
			var paramsData = {
				"jsonParas":_self.$AesUtil.encrypt(encodeURIComponent(JSON.stringify(params)))
			}	
			//重新获取一次token，防止接口返回认证失败系统重新获取的token未被使用
			_self.token = _self.$myFunction.appStorage('wuLuToken').token;				
			uni.request({
				url:  _self.$myFunction.appConfig().serverAddress+'productionDetail',
				data: paramsData,
				method : "POST",
				header : {
					'content-type':'application/x-www-form-urlencoded',
					'Authentication':_self.token
				},					
				success: data => {
					_self.$myFunction.displayLog("服务器返回数据："+JSON.stringify(data));
					uni.hideToast();
					if (data.data.code == 200) {
						_self.production = data.data.data.productionDto;	
						//获取课程对应的题目列表
						_self.getList("ICAO_P2");
					}else{
						//如果请求数据因token认证失败，则清空缓存token
						if(data.data.message.indexOf("接口访问未认证") != -1){
							uni.setStorage({
								key: 'wuLuToken',
								data: "",
								success: function () {	
									_self.$myFunction.displayLog("清空缓存token");
									//触发重新获取token
									_self.$myFunction.getToken();
									// 关闭所有页面，打开到应用内的某个页面。
									_self.$myFunction.displayLog("重加载当前页面");
									uni.reLaunch({
										url: '/pages/study/ICAOTopic'
									});
								}
							});
						}else{
							uni.showToast({title: "发生错误，请重试",icon: 'none'});
						}	
					}
				},
				fail: (data, code) => {
					uni.hideToast();
					uni.showToast({title: '连接失败...',icon: 'none'});
				}					
			});				
		},
		// 获取题目列表
		getList: function(content){
			uni.showToast({
				title: '请稍后...',
				duration:_self.$myFunction.appConfig().requestWaitTime,
				icon: 'none',
			});
			var params = {
				'field1':content,
				'pageNum':_self.pageNum,
				'pageSize':_self.pageSize,
				'field':"createTime",
				'createTimeTo':_self.createTimeTo,
				'order':'asc',
				'status':"1"
			};	
			
			//重新获取一次token，防止接口返回认证失败系统重新获取的token未被使用
			_self.token = _self.$myFunction.appStorage('wuLuToken').token;
			uni.request({
				url:  _self.$myFunction.appConfig().serverAddress+'topicList',
				data: params,
				method : "POST",
				header : {
					'content-type':'application/x-www-form-urlencoded',
					'Authentication':_self.token
				},		
				success: data => {
					// 刷新完毕后关闭刷新
					uni.hideToast();
					// uni.stopPullDownRefresh();
					// _self.$myFunction.displayLog("服务器返回数据："+JSON.stringify(data));					
					if (data.data.code == 200) {
						//总记录数
						var total = data.data.data.total;
						// _self.$myFunction.displayLog("服务器返回数据总记录数："+total);
						var objectsData=data.data.data.rows;
						// _self.$myFunction.displayLog("服务器返回当前查询条件记录数："+objectsData.length);						
						if(total == 0){//查询到0条记录
							return;
						}else{
							_self.choice[2] = total;//记录题目数量
							if(_self.showLoadMore){//触底加载数据
								if(_self.objects.length == total){
									_self.loadMoreText = "没有更多数据了";
									_self.pageNum = 1;
								}else if(_self.objects.length < total){//后台有未加载数据
									//以用户打开界面那一刻作为时间参考点
									//两种情况：
									//1、后台有未加载历史数据
									//2、后台有新增数据（此种情况不处理，因为需要刷新列表才能将最新数据展示在最前方）
									//listObjectNum:总记录数-当前列表记录数
									for (let i = 0; i < objectsData.length; i++) {
										//避免第2种情况发生时循环过后列表会产生重复记录(有时间参数createTimeTo，此种情况不存在)
										// let duplicateRecord = false;
										// for(let j = 0;j<_self.objects.length;j++){
										// 	if(_self.objects[j].id == objectsData[i].id){
										// 		duplicateRecord = true;
										// 	}
										// }
										// if(!duplicateRecord){
											_self.objects.push(objectsData[i]);
										// }
									}
									//返回的行数小于pageSize，证明数据已全部加载完毕
									if(objectsData.length<_self.pageSize){
										_self.loadMoreText = "没有更多数据了";
									}else{
										_self.loadMoreText = "加载更多";
									}
								}else if(_self.objects.length > total){//后台有删除数据
									//后台有数据被删除时不做数据处理，即前端显示有已被删除的数据
									//此时，当点击记录查看详情时应提示"此发布已删除"
									_self.loadMoreText = "没有更多数据了";
								}
							}else{//普通重新加载
								_self.objects.splice(0);	
								_self.lists.splice(0);
								for (let i = 0; i < objectsData.length; i++) {
									_self.objects.push(objectsData[i]);
									
									// {
									// 	title: "我们都一样",
									// 	singer: "张杰",
									// 	epname: "杰哥精选",
									// 	coverImgUrl: "https://7465-test01-632ffe-1258717418.tcb.qcloud.la/personal/player/images/jie02.jpg?sign=00e5e68d81145037000a162e2220736a&t=1556345760",
									// 	src: "https://7465-test01-632ffe-1258717418.tcb.qcloud.la/personal/player/song/%E6%88%91%E4%BB%AC%E9%83%BD%E4%B8%80%E6%A0%B7%20-%20%E5%BC%A0%E6%9D%B0.mp3?sign=008d62b6bea06a8a6814b5f284fac0ac&t=1556345730"
									// 	},
									
									let listsTemp = {};
									//id
									listsTemp.id = objectsData[i].id;
									//题目
									listsTemp.title = objectsData[i].field29;
					
									listsTemp.singer = '';
								
									listsTemp.epname = '';
								
									listsTemp.coverImgUrl = _self.topicImageSrc+_self.production.field1+'/'+objectsData[i].id+'/'+objectsData[i].field31;
									
									// 音频文件
									listsTemp.src = _self.topicImageSrc+_self.production.field1+'/'+objectsData[i].id+'/'+objectsData[i].field30;
									// 原文
									listsTemp.field11 = objectsData[i].field32;
									// 翻译
									listsTemp.field14 = objectsData[i].field33;
									_self.lists.push(listsTemp);
								}
								_self.$myFunction.displayLog("播放列表："+JSON.stringify(_self.lists));
								//播放列表读取成功再初始化播放器
								_self.playerInit();
							}
						}
					}else{
						//如果请求数据因token认证失败，则清空缓存token
						if(data.data.message.indexOf("接口访问未认证") != -1){
							uni.setStorage({
								key: 'wuLuToken',
								data: "",
								success: function () {	
									_self.$myFunction.displayLog("清空缓存token");
									//触发重新获取token
									_self.$myFunction.getToken();
									// 关闭所有页面，打开到应用内的某个页面。
									_self.$myFunction.displayLog("重加载当前页面");
									uni.reLaunch({
										url: '/pages/study/ICAO_P2Topic'
									});
								}
							});
						}else{
							_self.$myFunction.displayLog("题目列表读取失败："+JSON.stringify(data));
							uni.hideToast();
							uni.showToast({title: '连接失败...',icon: 'none'});
						}	
					}
				},
				fail: (data, code) => {
					uni.hideToast();
					uni.showToast({title: '连接失败...',icon: 'none'});
				}
			});
		},
		
	},
	components:{
		gracePage
	}
}
</script>
<style scoped>
/* .grace-player{padding:30rpx;} */
.grace-player-title{text-align:center; line-height:50rpx; font-size:30rpx; font-weight:bold;}
.grace-player-poster{padding:30px; line-height:0; text-align:center;}
.grace-player-poster-img{width:380rpx; height:100rpx; border-radius:300rpx; box-shadow:0rpx 2rpx 2rpx #323232;}
@keyframes grace-rotate360{0%{transform:rotate(0deg);} 50%{transform:rotate(180deg);} 100%{transform:rotate(360deg);}}
/* .grace-playing{animation:grace-rotate360 6000ms infinite linear;} */
.grace-player-console{padding:20rpx 10rpx; display:flex; flex-direction:row; align-items:center; justify-content:space-between;}
.grace-player-tool{width:100rpx; line-height:100rpx; text-align:center; font-size:50rpx; display:block; flex-shrink:0; color:#FFFFFF;}
.grace-player-console-c{width:400rpx; display:flex; flex-direction:row; justify-content:space-between;}
@font-face{
	font-family : "grace-playerfont";
	font-weight : normal;
	font-style  : normal;
	src         : url('@/static/gracePlayer.ttf') format('truetype');
}
.graceplayer-icons{font-family:"grace-playerfont"; font-style:normal;}
.graceplayer-list{width:100%; height:1000rpx; background-color:#FFFFFF; position:absolute; left:0; bottom:0; z-index:9999;}
.grace-shade{position:fixed; width:100%; height:100%; left:0; top:0; background-color:rgba(0,0,0,0.5); bottom:0; overflow:hidden; z-index:9998; display:flex; justify-content:center; align-items:center;}
.graceplayer-list-item{padding:25rpx 0rpx; margin:5rpx 30rpx; border-bottom:1px solid #373A3F; line-height:50rpx; font-size:30rpx; color:#FFFFFF;}
.graceplayer-list-item-singer{color:#888888; font-size:26rpx; margin-left:50rpx;}
.graceplayer-list-item-this{color:#64CDA5 !important; font-weight:bold;}
	/* 按钮 */
	.demo{display:flex; flex-wrap:nowrap; border-left:1px solid #F8F8F8;}
	.demo view{width:100%; text-align:center; margin:40rpx;}
	/* 进度条样式 */
	.progress-bar {
		position: relative;
		width: 100%;
		background-color: #f2f2f2;
		border-radius: 16rpx;
	}
	.progress {
		position: absolute;
		top: 0;
		left: 0;
		height: 100%;
	}
	.grace-sg-slider-bar{position:absolute; left:0; top:0; border-radius:50rpx; font-size:30rpx; text-align:center; color:#323232; overflow:hidden;}
	

</style>